import { messages, queryCurrencyPrecision, mulCalculate, deepFullCopy, currencyPrecisionCal } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Spin, Input, DatePicker, Row, Col, Icon, Popover, Form, Select, InputNumber, Button, message, Modal } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
import moment from 'moment';
import Invoice from 'containers/my-account/invoice';
import 'styles/my-account/create-invoice.scss';
import expenseService from 'containers/my-account/expense.service';
import errorMessage from "share/errorMessage";
import Condition from 'components/condition';
const { If, Else } = Condition;
import FileUpload from 'components/file-upload'
import IeFileUpload from 'components/template/ie-file-upload/ie-file-upload'
import ImageUpload from 'components/image-upload'
import IeImgUpload from 'components/template/ie-file-upload/ie-img-upload'
import InvoiceMoreInfoEdit from 'containers/my-account/components/invoice-more-info-edit'
import dataSources from 'containers/my-account/data-sources/data-sources';
const { showUserInfoOptions } = dataSources;

class CreateInvoice extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      currentStep: 0,
      checking: false,
      warning: "",
      taxRates: [],
      invoiceTypes: [],
      recordTaxRateConfig: false,//补录税率配置，当查验返回R_2002，需要强制显示税率／税额／不含税金额控件。切换发票类型取消。
      recordTaxAmountConfig: false,//补录税率配置，税额合计特殊处理
      additionalRecordingPriceAmountConfig: false,//补录价税合计配置，当查验返回R_2007，需要强制显示价税合计控件。切换发票类型取消。
      recordNonVATinclusiveAmountConfig: false,//补录税率配置,金额合计特殊处理
      receiptConfigList: [],//发票控件配置对象信息
      canSubmit: true,
      resultReceipt: {},
      beforeReceipt: {},
      companyOpenInvoice: false, //公司是否开通了票++
      invoiceOptionsFetching: false,
      receiptTipImages: {}, // 发票提醒图片
      imageIsUploading: false, //发票图片是否正在上传
      bagSaving: false,
      moreInfo: JSON.parse(props.receipt.moreInfo || "{}"),
      invoiceInfo: deepFullCopy(props.receipt), //发票详情
      auditSaving: false,
      showOCRFlag: false, //是否开通OCR
      imageResult: undefined,
      isChange: false,
      isChangeInfo: undefined
    }
  }

  componentDidMount() {
    this.getTitleListByEntity();
    this.getTaxRates();
    this.getInvoiceType();
  }

  //获取发票抬头，判断公司是否开票++
  getTitleListByEntity = () => {
    const { user, userOID } = this.props;
    this.setState({ loading: true });
    expenseService.getTitleList(userOID || (this.props.expenseReport || {}).applicantOID || user.userOID).then(res => {
      this.setState({
        loading: false,
        companyOpenInvoice: res.data.showCheckInvoiceFlag,
        showOCRFlag: res.data.showOCRFlag
      }, () => {
        this.initReceiptValue(this.props.receipt);
      })
    });
  }
  //获取所有税率
  getTaxRates = () => {
    expenseService.getRateByInvoiceType('').then(res => {
      this.setState({ taxRates: res.data.sort((a, b) => a.taxRateValue > b.taxRateValue || -1) })
    });
  }

  getInvoiceType = () => {
    this.setState({ invoiceOptionsFetching: true });
    expenseService.getInvoiceTypeList().then(res => {
      this.setState({
        invoiceTypes: res.data.rows,
        invoiceOptionsFetching: false
      })
    });
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.receipt !== this.props.receipt) {
      this.initReceiptValue(nextProps.receipt);
    }
  }
  //验证多发票逻辑
  validateMoreReceiptList = (invoiceInfo, isValidateRate = false) => {
    let { receiptList, receiptOperateScene, receiptIndex, pageFrom } = this.props;
    let tip = '';
    if (!(receiptOperateScene === 3 && receiptList.length === 1) && pageFrom !== "OCR") {
      receiptList.length > 0 && receiptList.some((item, index) => {
        if (
          !(receiptOperateScene === 3 && index === receiptIndex) &&
          invoiceInfo.invoiceTypeNo === item.invoiceTypeNo
        ) {
          //机票行程单单独验证号码、其他均需要代码号码均有值才验证
          if (String(invoiceInfo.invoiceTypeNo) === "150") {
            if (invoiceInfo.billingNo && invoiceInfo.billingNo === item.billingNo) {
              tip = messages('my-account.key242')/*当前发票已存在，请勿重复添加*/;
              return true;
            }
          } else if (
            invoiceInfo.billingCode && invoiceInfo.billingNo &&
            (invoiceInfo.billingCode === item.billingCode) &&
            (invoiceInfo.billingNo === item.billingNo)
          ) {
            tip = messages('my-account.key242')/*当前发票已存在，请勿重复添加*/;
            return true;
          }
        }

        if (item.vatInvoice || invoiceInfo.vatInvoice) { //有专票
          if (item.vatInvoice !== invoiceInfo.vatInvoice) { //发票类型不同
            tip = messages('my-account.key296')/*增值税专用发票与非增值税专用发票不能在一条费用行申请，请拆分费用行填写*/;
            return true;
          }
          if (isValidateRate && item.taxRate !== invoiceInfo.taxRate) { //税率不同
            if (pageFrom === undefined || pageFrom === 'myView') { //税率只需要在员工端校验 bug 33902
              tip = messages('my-account.key297')/*由于您上传的增值税专用发票的税率不同，请拆分费用行填写*/;
              return true;
            }
          }
        }
      });
    }
    return tip;
  };

  //获取发票补录信息
  checkSuccessByCode = (resultCode) => {
    let checkSuccess = true;
    if (resultCode === 'R_2007') {
      this.setState({
        additionalRecordingPriceAmountConfig: true
      });
      checkSuccess = false;
    }
    if (resultCode === 'R_2008') {
      this.setState({
        additionalRecordingPriceAmountConfig: true,
        recordTaxRateConfig: true
      });
      checkSuccess = false;
    }
    if (resultCode === 'R_2002') {
      this.setState({
        recordTaxRateConfig: true
      });
      checkSuccess = false;
    }
    return checkSuccess
  };
  // 票易通错误信信息检查
  checkPYTerror = (errorList) => {
    if (!errorList) return
    return errorList.find((obj) => {
      return obj.code === 'R_2015'
    })
  }
  // 查验发票
  testInvoice = (invoiceInfo) => {
    this.setState({ checking: true });
    const { invoiceBagId, expenseReportId, user, userOID, fromVICP, onCreate, close, receiptOperateScene, id } = this.props;
    const { showOCRFlag, invoiceTypes } = this.state;
    let type = null;
    if (invoiceBagId)
      type = 'bag';
    if (expenseReportId)
      type = 'expense_report';
    if (fromVICP)
      type = 'VICP';
    console.log("receiptOperateScene", receiptOperateScene)
    console.log("invoiceInfo", invoiceInfo)
    console.log('type', type)
    if (receiptOperateScene === 2 || invoiceInfo.cardsignType === 'HAND') {
      // let newInvoiceInfo = invoiceInfo;
      invoiceInfo.receiptLabels = [];
      invoiceInfo.type = invoiceTypes.filter(item => item.value === invoiceInfo.invoiceTypeNo)[0].messageKey;
      expenseService.getInvoiceCheck(id, [invoiceInfo]).then(res => {
        console.log("111111", res)
        let data = res.data.receipts[0];
        data.vatInvoice = data.vatInvoice ? true : false;

        // 票易通校验错误信息弹窗
        if (res.data.canCreateExpense === 'N' && res.data.errorListV2) {
          let errorObj = this.checkPYTerror(res.data.errorListV2)
          if (errorObj) {
            Modal.error({
              title: errorObj.title || '',
              content: errorObj.message || '',
            });
            this.setState({ checking: false });
            return
          }
        }

        if (this.props.createType === 2) {
          this.setState({ checking: true });
          this.saveReceipt(data).then(result => {
            this.setState({ checking: false });
            if (result) {
              onCreate && onCreate(result, showOCRFlag)
            }
          }).catch(e => {
            this.setState({ checking: false });
          });
          return;
        } else {
          onCreate && onCreate(data, showOCRFlag);
        }
      })
      // if (invoiceInfo.vatInvoice) {

      // } else {
      //   invoiceInfo.vatInvoice = false;
      // }
      // this.setState({checking: true});
      // if (this.props.createType === 2) {
      //   this.setState({checking: true});
      //   this.saveReceipt(invoiceInfo).then(result => {
      //     this.setState({checking: false});
      //     if (result) {
      //       onCreate && onCreate(result, showOCRFlag)
      //     }
      //   }).catch(e => {
      //     this.setState({checking: false});
      //   });
      //   return;
      // } else {
      //   onCreate && onCreate(invoiceInfo, showOCRFlag);
      // }
    } else {
      expenseService.testInvoice(invoiceInfo, userOID || user.userOID, type, invoiceBagId || expenseReportId).then(res => {
        // let data = type ? res.data : res.data[0];
        let data = res.data;
        let receipt = data.invoiceInfo;
        this.setState({ checking: false });
        if (!this.checkSuccessByCode(data.resultCode)) {
          message.info(data.msg);
          return;
        }
        if (!receipt) {
          message.error(data.msg);
          return;
        }
        // 后端自动补全了补录信息
        if (data.resultCode === "R_2010") {
          message.success(data.msg);
        }
        let tip = this.validateMoreReceiptList(receipt, true);
        if (tip) {
          Modal.info({
            title: tip
          });
          return;
        }
        // 逻辑修改 200成功就跳转生成费用查看发票
        let errorList = data.errorList;
        errorList.length > 0 && errorList.forEach(item => {
          item.name = item.title;
          item.toast = item.message;
        });
        receipt.receiptLabels = errorList;
        console.log("invoiceBagId", invoiceBagId)
        console.log('expenseReportId', expenseReportId)
        console.log("fromVICP", fromVICP)
        if (data.isOk === 'Y' && !invoiceBagId && !expenseReportId && !fromVICP) {
          if (this.props.createType === 2) {
            this.setState({ checking: true });
            this.saveReceipt(receipt).then(result => {
              this.setState({ checking: false });
              if (result) {
                onCreate && onCreate(result, showOCRFlag)
              }
            }).catch(e => {
              this.setState({ checking: false });
            });
            return;
          } else {
            onCreate && onCreate(receipt, showOCRFlag);
          }
          return;
        }
        // if (data.isOk === 'N') {
        //   message.error(data.msg);
        //   return;
        // }
        receipt.resultCode = data.resultCode;
        this.setState({
          resultReceipt: receipt,
          beforeReceipt: invoiceInfo,
          currentStep: 1,
          canSubmit: false
        })
      }).catch(e => {
        console.error(e)
        errorMessage(e.response);
        this.setState({ checking: false });
      });
    }
  };

  //保存发票For费用
  saveReceipt = (receipt) => {
    let { invoiceOID, invoiceBagId, expenseReportId, fromVICP } = this.props;
    if (!receipt.invoiceOID && invoiceOID) {
      receipt.invoiceOID = invoiceOID;
    }
    return new Promise((resolve, reject) => {
      let type = null;
      if (invoiceBagId)
        type = 'bag';
      if (expenseReportId)
        type = 'expense_report';
      if (fromVICP)
        type = 'VICP';
      expenseService.financialAuditInvoice(receipt, type, invoiceBagId || expenseReportId).then(res => {
        if (res.data.code === '0000') {
          message.success(messages('common.save.success', { name: '' }));
          return resolve(res.data.rows);
        }
        else {
          let errorList = res.data.rows.errorList;
          let warningInfo = [];
          errorList && errorList.length > 0 && errorList.map(item => {
            warningInfo.push(`${item.title}${item.title ? ':' : ''}${item.message}`);
          })
          message.error(warningInfo.join('/'));
          return reject(false);
        }
      }).catch(e => {
        errorMessage(e.response);
        return reject(false);
      })
    })
  }
  //提交
  handleSubmit = (e) => {
    if (e) e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let { invoiceOID, receipt } = this.props;
        const { imageIsUploading, moreInfo } = this.state;
        console.log("111111111", this, values)
        if (imageIsUploading) {
          message.warning(messages('my-account.key249')/*图片上传中，请稍后*/);
          return
        }
        //区块链发票
        if (receipt.blockchain && values.checkCode && values.checkCode.length !== 5) {
          message.warning(messages('my-account.key313')/*区块链发票校验码仅支持5位数字或字母*/);
          return
        }
        //发票类型编码=10且校验码字符串长度为5，则认为是区块链发票，不可保存
        if (values.invoiceTypeNo === '10' && values.checkCode && values.checkCode.length === 5) {
          Modal.info({
            title: messages('my-account.key305')/*增值税电子普通发票需输入校验码后六位数字。若票面仅有5位校验码，则为区块链发票，需要采用其他方式录入发票。*/
          });
          return
        }
        if (values.checkCode && (!/^[0-9]+$/.test(values.checkCode) || values.checkCode.length !== 6)) {
          message.warning(messages('my-account.key306')/*校验码仅支持6位数字*/);
          return
        }
        //价税合计金额大于8位数，不可保存。
        if (values.priceTaxAmount > 1000000000) {
          message.warning(messages('my-account.key169', { arg1: messages('my-account.key334')/*10亿*/ })/*最大值不能超过{arg1}*/);
          return
        }
        if (values.invoiceTypeNo === '08') {
          let list = this.state.imageResult;
          let params = [];
          list && list.map(item => {
            params.push({
              attachmentOID: item.attachmentOID,
              fileURL: item.fileURL,
              fileName: item.fileName,
              fileType: item.fileType,
            });
          })
          const serviceName = "checkOFD";
          if (values.slicingAttachmentOID[0] && values.slicingAttachmentOID[0].fileType) {
            if (!['OFD'].includes(values.slicingAttachmentOID[0].fileType)) {
              message.warning('增值税电子专用发票，需上传OFD格式源文件')
              return
            }
          } else {
            if (!['OFD'].includes(receipt.originAttachment.fileType)) {
              message.warning('增值税电子专用发票，需上传OFD格式源文件')
              return
            }
          }
          if (params && params[0]) {
            if (!['OFD'].includes(params[0].fileType)) {
              message.warning('增值税电子专用发票，需上传OFD格式源文件')
              return
            }
          }
          // expenseService
          //   [serviceName](params)
          //   .then(res => {
          //     if (res.data.success) {

          //     } else {
          //       message.warning('增值税电子专用发票，需上传OFD格式源文件');
          //       return
          //     }
          //   }).catch(e => {
          //     console.log('1111122222')
          //     message.warning('增值税电子专用发票，需上传OFD格式源文件');
          //     return
          //   })
        }

        //, '10001' 医疗报销单 不控制 PDF / OFD
        if (['10', '20', '14'].includes(values.invoiceTypeNo)) {
          if (values.slicingAttachmentOID[0] && values.slicingAttachmentOID[0].fileType) {
            if (!['OFD', 'PDF'].includes(values.slicingAttachmentOID[0].fileType)) {
              if (values.invoiceTypeNo === '14') {
                message.warning('需要上传PDF或者OFD文件')
              } else {
                message.warning('电子发票，需要上传PDF或者OFD文件')
              }
              return
            }
          } else {
            let list = this.state.imageResult;
            let params = [];
            list && list.map(item => {
              params.push({
                attachmentOID: item.attachmentOID,
                fileURL: item.fileURL,
                fileName: item.fileName,
                fileType: item.fileType,
              });
            })
            if (params && params[0]) {
              if (!['OFD', 'PDF'].includes(params[0].fileType)) {
                if (values.invoiceTypeNo === '14') {
                  message.warning('需要上传PDF或者OFD文件')
                } else {
                  message.warning('电子发票，需要上传PDF或者OFD文件')
                }
                return
              }
            } else {
              if (!['OFD', 'PDF'].includes(receipt.originAttachment.fileType)) {
                if (values.invoiceTypeNo === '14') {
                  message.warning('需要上传PDF或者OFD文件')
                } else {
                  message.warning('电子发票，需要上传PDF或者OFD文件')
                }
                return
              }
            }
          }
        }
        // 财务修改发票类型判断
        if (this.state.isChangeInfo && this.state.isChangeInfo.oldTypeName && this.props.createType === 2) {
          console.log("财务修改发票类型判断", this.state.isChangeInfo.oldTypeName, values.invoiceTypeNo)
          let oldData = this.state.invoiceTypes.filter(item => item.messageKey === this.state.isChangeInfo.oldTypeName)[0];
          // 旧数据是 电子票
          if (['10', '08', '20', '10001'].includes(oldData.value)) {
            if (!['10', '08', '20', '10001'].includes(values.invoiceTypeNo)) {
              message.warning('不可将电子票改为纸质票')
              return
            }
          } else {
            if (['10', '08', '20', '10001'].includes(values.invoiceTypeNo)) {
              message.warning('不可将纸质票改为电子票')
              return
            }
          }
        }
        let invoiceInfo = deepFullCopy(this.state.invoiceInfo);
        invoiceInfo.cardsignType = receipt ? (receipt.cardsignType || 'HAND') : 'HAND';
        receipt.pdfUrl && (invoiceInfo.pdfUrl = receipt.pdfUrl);
        receipt.slicingAttachment && (invoiceInfo.slicingAttachment = receipt.slicingAttachment);
        invoiceInfo.invoiceOID = invoiceOID;
        invoiceInfo.billingNo = values.invoiceNumber;
        if (receipt && receipt.id) {
          invoiceInfo.id = receipt.id;
        }
        invoiceInfo.billingCode = values.invoiceCode ? values.invoiceCode.toUpperCase() : values.invoiceCode;
        invoiceInfo.checkCode = values.checkCode;
        Object.assign(invoiceInfo, values);
        if (values.invoiceDate) {
          invoiceInfo.billingTime = (new Date(values.invoiceDate).getTime() / 1000).toFixed(0);
        }
        invoiceInfo.receiptTypeNo = invoiceInfo.invoiceTypeNo;
        if (invoiceInfo.nonVATinclusiveAmount) {
          invoiceInfo.feeWithoutTax = mulCalculate(invoiceInfo.nonVATinclusiveAmount, 100);
        }
        else {
          invoiceInfo.feeWithoutTax = invoiceInfo.nonVATinclusiveAmount;
        }
        if (invoiceInfo.taxAmount) {
          invoiceInfo.tax = mulCalculate(invoiceInfo.taxAmount, 100);
        }
        else {
          invoiceInfo.tax = invoiceInfo.taxAmount;
        }
        if (invoiceInfo.nonDeductibleAmount) {
          invoiceInfo.nonDeductibleAmount = mulCalculate(invoiceInfo.nonDeductibleAmount, 100);
        }
        if (this.checkInvoiceRender('priceTaxAmount') || this.state.additionalRecordingPriceAmountConfig) {
          if (invoiceInfo.priceTaxAmount) {
            invoiceInfo.fee = mulCalculate(invoiceInfo.priceTaxAmount, 100);
          } else {
            invoiceInfo.fee = invoiceInfo.priceTaxAmount;
          }
        }
        let attachment = invoiceInfo.slicingAttachmentOID;
        if (typeof attachment === 'object') {
          if ((attachment && attachment[0] && attachment[0].attachmentOID)) {
            invoiceInfo.slicingAttachmentOID = attachment[0].attachmentOID
          } else {
            invoiceInfo.slicingAttachment = null;
            invoiceInfo.slicingAttachmentOID = null;
          }
        }
        if (!this.checkInvoiceRender('image') && invoiceInfo.cardsignType !== 'OCR') {
          invoiceInfo.slicingAttachment = null;
          invoiceInfo.slicingAttachmentOID = null;
        }
        if (invoiceInfo.owner) {
          invoiceInfo.receiptOwner = invoiceInfo.owner
        }
        invoiceInfo.moreInfo = JSON.stringify(moreInfo);
        invoiceInfo.moreInfoLabel = this.props.receipt.moreInfoLabel;
        invoiceInfo.showUserInfo = values.showUserInfo || "";
        if (invoiceInfo.originAttachment) {
          invoiceInfo.attachmentOID = invoiceInfo.originAttachment.attachmentOID
        } else {
          invoiceInfo.attachmentOID = invoiceInfo.slicingAttachmentOID;
        }
        if (this.state.imageResult && this.state.imageResult[0]) {
          invoiceInfo.attachmentOID = this.state.imageResult[0].attachmentOID;
          invoiceInfo.originAttachment = this.state.imageResult[0];
          invoiceInfo.slicingAttachment = this.state.imageResult[0];
          invoiceInfo.slicingAttachmentOID = this.state.imageResult[0].attachmentOID;
        }
        this.testInvoice(invoiceInfo);
      }
    })
  };

  //清空补录相关信息
  clearRecordFormItem = () => {
    this.setState({
      recordTaxRateConfig: false,
      recordTaxAmountConfig: false,
      recordNonVATinclusiveAmountConfig: false,
      additionalRecordingPriceAmountConfig: false
    })
  }

  //获取数据源
  getCurrentReceiptData = (receipt) => {
    const { currencyList } = this.props;
    let target = {};
    if (receipt) {
      target.invoiceTypeNo = receipt.invoiceTypeNo;
      if (receipt.billingTime) {
        target.invoiceDate = moment(new Date(receipt.billingTime * 1000))
      }
      target.invoiceCode = receipt.billingCode;
      target.invoiceNumber = receipt.billingNo;
      //若未识别到币种或币种未启用，则置空
      if (currencyList && currencyList.some(item => item.currency === receipt.vatInvoiceCurrencyCode)) {
        target.vatInvoiceCurrencyCode = receipt.vatInvoiceCurrencyCode || undefined;
      } else {
        target.vatInvoiceCurrencyCode = undefined;
      }
      console.log('receipt', receipt)
      target.taxRate = receipt.taxRate ? receipt.taxRate : receipt.invoiceGoods && receipt.invoiceGoods[0] ? Number(receipt.invoiceGoods[0].taxRate) / 100 : null;
      // target.taxRate = receipt.taxRate
      if (target.taxRate != null) {
        this.setState({ recordTaxRateConfig: true })
      } else {
        this.setState({ recordTaxRateConfig: false })
      }
      if (receipt.feeWithoutTax != null) {
        target.nonVATinclusiveAmount = receipt.feeWithoutTax / 100;
        this.setState({ recordNonVATinclusiveAmountConfig: true })
      }
      else {
        this.setState({ recordNonVATinclusiveAmountConfig: false })
      }
      if (receipt.tax != null) {
        target.taxAmount = receipt.tax / 100;
        this.setState({ recordTaxAmountConfig: true })
      } else {
        this.setState({ recordTaxAmountConfig: false })
      }
      if (receipt.tmpFee != null) {
        target.priceTaxAmount = receipt.tmpFee / 100;
      }
      if (receipt.nonDeductibleAmount != null) {
        target.nonDeductibleAmount = receipt.nonDeductibleAmount / 100;
      }
      if (receipt.fee != null) {
        this.setState({ additionalRecordingPriceAmountConfig: true });
        target.priceTaxAmount = receipt.fee / 100;
      } else {
        this.setState({ additionalRecordingPriceAmountConfig: false })
      }
      target.checkCode = receipt.checkCode ? receipt.checkCode.slice(-6) : receipt.checkCode;
      target.owner = receipt.receiptOwner;
      target.showUserInfo = receipt.showUserInfo;
    } else {
      target.invoiceDate = moment(new Date());
    }
    return target;
  };

  //初始化值发票控件值
  initReceiptValue = (receipt) => {
    console.log('初始化值发票控件值')
    let currentReceipt;
    //编辑
    if (receipt && JSON.stringify(receipt) !== "{}") {
      currentReceipt = this.getCurrentReceiptData(receipt);
      if (!receipt.invoiceTypeNo) {
        this.props.form.setFieldsValue(currentReceipt);
        return
      }
      if (Number(receipt.invoiceTypeNo) === 150) {
        currentReceipt.nonDeductibleAmount = currentReceipt.nonDeductibleAmount === undefined ? 50 : currentReceipt.nonDeductibleAmount;
        //【总金额】= 【价税合计】+【不可抵扣】
        currentReceipt.totalAmount = (currentReceipt.priceTaxAmount || 0) + (currentReceipt.nonDeductibleAmount || 0);
      }
      //查询控件显示
      this.queryReceiptShow(currentReceipt.invoiceTypeNo).then(receiptConfigList => {
        this.setState({
          receiptConfigList
        }, () => {
          this.props.form.setFieldsValue({ invoiceTypeNo: currentReceipt.invoiceTypeNo });
        })
        //查询支持汇率
        this.queryDefaultReceiptRate(currentReceipt.invoiceTypeNo).then(taxRates => {
          this.setState({ taxRates }, () => {
            currentReceipt = this.editExitFormItem(this.props.form.getFieldsValue(), currentReceipt, false);
            this.props.form.setFieldsValue(currentReceipt);
          })
        });
      });
      //获取发票提示图片
      this.getTipImg(currentReceipt.invoiceTypeNo);
    }
    this.checkSuccessByCode(receipt.resultCode)
  };

  handleReRenderFormItemForReceiptNo = () => {
    const { getFieldValue, setFieldsValue } = this.props.form;
    let currentReceipt, invoiceTypeNoValue = getFieldValue('invoiceTypeNo');
    currentReceipt = this.props.receipt;
    currentReceipt = this.getCurrentReceiptData(currentReceipt);
    currentReceipt.totalAmount = currentReceipt.priceTaxAmount;
    currentReceipt = this.editExitFormItem(this.props.form.getFieldsValue(), currentReceipt, false);
    if (Number(invoiceTypeNoValue) === 150) {
      //【总金额】= 【价税合计】+【不可抵扣】
      currentReceipt.nonDeductibleAmount = currentReceipt.nonDeductibleAmount === undefined ? 50 : currentReceipt.nonDeductibleAmount;
      if (currentReceipt.totalAmount || currentReceipt.totalAmount === 0) {
        currentReceipt.priceTaxAmount = currentReceipt.totalAmount - currentReceipt.nonDeductibleAmount;
      }
    }
    setFieldsValue(currentReceipt);
  };
  //发票类型改变
  handleReceiptNoChange = (receiptNo) => {
    //查询控件显示
    console.log("11111", receiptNo, this)
    this.queryReceiptShow(receiptNo).then(receiptConfigList => {
      this.setState({
        receiptConfigList,
        isChange: true,
        isChangeInfo: {
          receiptNo: receiptNo,
          oldTypeName: this.state.invoiceInfo.type
        }
      }, () => {
        //初始化默认值
        this.handleReRenderFormItemForReceiptNo();
        //查询默认汇率
        this.checkInvoiceRender('taxRate') && this.queryDefaultReceiptRate(receiptNo).then(taxRates => {
          //汇率默认值设置
          this.setState({ taxRates }, () => {
            taxRates.length > 0 && taxRates.map(rate => {
              if (rate.defaultValue) {
                let currentValue = this.getFormItemValue('taxRates');
                if (currentValue != rate.taxRateValue) {
                  this.props.form.setFieldsValue({ taxRate: rate.taxRateValue });
                  this.handleChangeTaxRate(rate.taxRateValue);
                }
              }
            });
          })
        })
      });
    });
    //获取发票提示图片
    this.getTipImg(receiptNo);
  };

  //获取表单值
  getFormItemValue = (formItemId) => {
    const { getFieldsValue, getFieldValue } = this.props.form;
    return getFieldsValue().hasOwnProperty(formItemId) ? getFieldValue(formItemId) : "";
  };

  //获取发票对应公司
  getReceiptCompany = () => {
    let company;
    let { documentaryCompany } = this.props;
    if (documentaryCompany && documentaryCompany.id) {
      company = documentaryCompany;
    } else {
      company = this.props.company;
    }
    return company;
  }
  //查询控件显示
  queryReceiptShow = (receiptNo) => {
    return new Promise((resolve, reject) => {
      let { companyOpenInvoice } = this.state;
      let company = this.getReceiptCompany();
      this.setState({ loading: true });
      expenseService.getReceiptDisplay(companyOpenInvoice, receiptNo, company.tenantId, company.setOfBooksId, company.id).then(res => {
        if (res.data && res.data.rows && res.data.rows.length > 0 && res.data.rows[0].hitValue) {
          this.setState({ loading: false });
          let receiptConfigList = JSON.parse(res.data.rows[0].hitValue);
          console.log("receiptConfigList", receiptConfigList)
          resolve(receiptConfigList)
        }
      }).catch(e => {
        this.setState({ loading: false });
        errorMessage(e.response);
        this.clearRecordFormItem();
        reject([]);
      });
    })
  }
  //查询默认汇率
  queryDefaultReceiptRate = (receiptNo) => {
    return new Promise((resolve, reject) => {
      expenseService.getRateByInvoiceType(receiptNo).then(res => {
        let taxRates = res.data.sort((a, b) => a.taxRateValue > b.taxRateValue || -1);
        resolve(taxRates)
      }).catch(e => {
        reject([])
      })
    })
  }

  //修改存在的FormItem项,isCoverFormItem是否覆盖form项
  editExitFormItem(formItems, inits, isCoverFormItem = false) {
    let exitVar = {}
    if (formItems && inits) {
      Object.keys(inits).map(item => {
        if (formItems.hasOwnProperty(item)) {
          if ((!isCoverFormItem && !formItems[item]) || isCoverFormItem) {
            if (inits[item] != undefined && inits[item] != null) {
              exitVar[item] = inits[item];
            }
          }
        }
      })
    }
    return exitVar;
  }

  /**
   * 税率改变时修改税额、不含税金额
   * @param value
   */
  handleChangeTaxRate = (value) => {
    const { getFieldsValue, setFieldsValue, getFieldValue } = this.props.form;
    let amount = getFieldValue('priceTaxAmount');
    let nonVATinclusiveAmount;
    if (getFieldsValue().hasOwnProperty('nonVATinclusiveAmount')) {
      nonVATinclusiveAmount = getFieldValue('nonVATinclusiveAmount');
    }
    let vatInvoiceCurrencyCodeValue = this.getFormItemValue('vatInvoiceCurrencyCode');
    let currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    if (Math.abs(Number(amount)) >= 0) {
      let nonVATinclusiveAmount = Number((amount / (1 + value)).toFixed(currencyPrecision));
      let taxAmount = Number((amount - nonVATinclusiveAmount).toFixed(currencyPrecision));
      if (getFieldsValue().hasOwnProperty('nonVATinclusiveAmount')) {
        setFieldsValue({ nonVATinclusiveAmount: nonVATinclusiveAmount });
      }
      if (getFieldsValue().hasOwnProperty('taxAmount')) {
        setFieldsValue({ taxAmount: taxAmount });
      }
    } else if (nonVATinclusiveAmount) {
      let priceTaxAmount = Number(+nonVATinclusiveAmount * (1 + value)).toFixed(currencyPrecision);
      let taxAmount = Number((priceTaxAmount - nonVATinclusiveAmount).toFixed(currencyPrecision));
      if (getFieldsValue().hasOwnProperty('priceTaxAmount')) {
        setFieldsValue({ priceTaxAmount: priceTaxAmount });
      }
      if (getFieldsValue().hasOwnProperty('taxAmount')) {
        setFieldsValue({ taxAmount: taxAmount });
      }
      setFieldsValue({ nonVATinclusiveAmount: this.getCurrencyPrecisionValue(nonVATinclusiveAmount) });
    }
  };
  /**
   * 税额改变时修改不含税金额
   * @param value
   */
  handleChangeTaxAmount = (value) => {
    const { getFieldsValue, setFieldsValue, getFieldValue } = this.props.form;
    let amount = getFieldValue('priceTaxAmount');
    //避免金额合计控件不显示，强行计算
    if (!getFieldsValue().hasOwnProperty('nonVATinclusiveAmount')) {
      return;
    }
    let nonVATinclusiveAmount = amount - value;
    if (isNaN(nonVATinclusiveAmount)) {
      //setFieldsValue({nonVATinclusiveAmount: this.getCurrencyPrecisionValue(nonVATinclusiveAmount)});
    } else {
      setFieldsValue({ nonVATinclusiveAmount: this.getCurrencyPrecisionValue(nonVATinclusiveAmount) });
    }
  };
  //获取币种金额值
  getCurrencyPrecisionValue = (value) => {
    let vatInvoiceCurrencyCodeValue = this.getFormItemValue('vatInvoiceCurrencyCode');
    let currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    return Number(Number(value).toFixed(currencyPrecision))
  };

  /**
   * 价税合计改变修改税额、不含税金额
   */
  handleChangePriceTaxAmount = (amount) => {
    const { getFieldsValue, setFieldsValue, getFieldValue } = this.props.form;
    let taxRate = getFieldValue('taxRate');
    let vatInvoiceCurrencyCodeValue = this.getFormItemValue('vatInvoiceCurrencyCode');
    let currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    if (Number(taxRate) >= 0) {
      amount = parseFloat(amount);
      if (isNaN(amount)) {
        amount = 0;
      }
      let nonVATinclusiveAmount = Number((amount / (1 + taxRate)).toFixed(currencyPrecision));
      let taxAmount = Number((amount - nonVATinclusiveAmount).toFixed(currencyPrecision));
      if (getFieldsValue().hasOwnProperty('nonVATinclusiveAmount')) {
        setFieldsValue({ nonVATinclusiveAmount: nonVATinclusiveAmount })
      }
      if (getFieldsValue().hasOwnProperty('taxAmount')) {
        setFieldsValue({ taxAmount: taxAmount })
      }
    }
  };

  //币种选择改变
  selectVatInvoiceCurrencyCodeChange = (value) => {
    let currcyAccuracyRelate = ['priceTaxAmount', 'taxAmount', 'nonVATinclusiveAmount'];
    let { getFieldsValue, setFieldsValue, getFieldValue } = this.props.form;
    currcyAccuracyRelate.map(item => {
      if (getFieldsValue().hasOwnProperty(item) && getFieldValue(item) !== undefined) {
        setFieldsValue({
          [item]: Number(currencyPrecisionCal(value, getFieldValue(item)))
        });
      }
    })
  };

  handleValidator = (rule, value, callback) => {  // 处理报错
    const { getFieldValue } = this.props.form;
    const priceTaxAmountValue = getFieldValue('priceTaxAmount');
    const { recordTaxAmountConfig, recordNonVATinclusiveAmountConfig } = this.state;
    let arrSpeech = {}, middleConfig;
    if (rule.field === 'taxAmount') {
      arrSpeech['speechOne'] = messages('my-account.key274')/*税额合计的绝对值不能大于价税合计的绝对值*/;
      arrSpeech['speechTwo'] = messages('my-account.key275')/*税额合计与价税合计的符号必须一致！*/;
      middleConfig = recordTaxAmountConfig;
    }
    if (rule.field === 'nonVATinclusiveAmount') {
      arrSpeech['speechOne'] = messages('my-account.key276')/*金额合计(不含税)的绝对值不能大于价税合计的绝对值*/;
      arrSpeech['speechTwo'] = messages('my-account.key277')/*金额合计(不含税)与价税合计的符号必须一致！*/;
      middleConfig = recordNonVATinclusiveAmountConfig;
    }
    if (Math.abs(value) > Math.abs(priceTaxAmountValue)) {  // 金额合计不能大于价税合计
      callback(arrSpeech['speechOne']);
    } else if (value > 0 && priceTaxAmountValue < 0 || priceTaxAmountValue > 0 && value < 0) {
      callback(arrSpeech['speechTwo']);
    } else {
      if ((middleConfig || this.checkInvoiceRender(rule.field, 2)) && (value === undefined || value === null)) {
        callback(messages('common.please.enter'));
      } else {
        callback();
      }
    }
  };

  //联动关系：【价税合计】=【总金额】-【不可抵扣】
  //价税合计变化，有税率时，重算税额和不含税金额：【价税合计】=【税额】+【不含税金额】
  handleAmountLinkage = (type, value = 0) => {
    const { setFieldsValue } = this.props.form;
    let priceTaxAmount = Number(this.getFormItemValue('priceTaxAmount') || 0);
    let totalAmount = this.getFormItemValue('totalAmount');
    let nonDeductibleAmount = Number(this.getFormItemValue('nonDeductibleAmount') || 0);
    let currencyCode = this.getFormItemValue('vatInvoiceCurrencyCode');
    let precision = queryCurrencyPrecision(currencyCode);
    value = Number(isNaN(value) ? 0 : value);
    //若总金额为空，需要计算总金额
    if (!totalAmount && totalAmount !== 0 && type !== 'totalAmount') {
      if (type === 'priceTaxAmount') { //价税合计
        setFieldsValue({ totalAmount: (value + nonDeductibleAmount).toFixed(precision) });
        this.handleChangePriceTaxAmount(value)
      }
      if (type === 'nonDeductibleAmount') { //不可抵扣
        setFieldsValue({ totalAmount: (value + priceTaxAmount).toFixed(precision) });
      }
    } else {
      if (type === 'priceTaxAmount') { //价税合计
        setFieldsValue({ nonDeductibleAmount: (totalAmount - value).toFixed(precision) });
        this.handleChangePriceTaxAmount(value)
      }
      if (type === 'totalAmount') { //总金额
        setFieldsValue({ priceTaxAmount: (value - nonDeductibleAmount).toFixed(precision) });
        this.handleChangePriceTaxAmount(value - nonDeductibleAmount)
      }
      if (type === 'nonDeductibleAmount') { //不可抵扣
        setFieldsValue({ priceTaxAmount: (totalAmount - value).toFixed(precision) });
        this.handleChangePriceTaxAmount(totalAmount - value)
      }
    }
  };

  //没有发票代码时是否显示formItem
  //因为OCR查验发票可能没有识别出发票代码但却有其它的值
  showItemWithoutCode = (type) => {
    const { receipt } = this.props;
    const { getFieldValue } = this.props.form;
    return (
      !getFieldValue('invoiceTypeNo') &&
      (receipt[type] || receipt[type] === 0)
    );
  };

  //修改更多信息
  handleMoreInfoChange = (isMoreInfo, value) => {
    if (isMoreInfo) {
      this.setState({ moreInfo: value })
    } else {
      let { invoiceInfo } = this.state;
      Object.keys(value).map(key => {
        invoiceInfo[key] = value[key]
      });
      this.setState({ invoiceInfo })
    }
  };

  /**
   * 判断是否需要展示【更多信息】
   * 需展示场景
   *    1: moreInfo字段有值且不为"{}"
   *    2: 【销售方名称、销售方纳税人识别号、购买方名称、购买方纳税人识别号】字段任意一个有值
   */
  isMoreInfoShow = () => {
    const { receipt } = this.props;
    const { receiptConfigList, isChange } = this.state;
    const needShowKey = ['payee', 'payeeNo', 'title', 'draweeNo'];
    let isShow = false;
    if (isChange) {
      receiptConfigList.map(item => {
        needShowKey.map(key => {
          if (item.valueCode === key && item.value === '30') {
            isShow = true;
          }
        })
      })
    } else {
      if (receipt.moreInfo && receipt.moreInfo !== "{}") {
        isShow = true
      }
    }
    // needShowKey.map(key => {
    //   if (receipt[key]) {
    //     isShow = true
    //   }
    // });
    return isShow
  };

  //发票录入修改
  renderInvoiceArea = () => {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { currencyList, invoiceUserFp, onBack, currency, language, receipt } = this.props;
    const { taxRates, invoiceTypes, recordTaxRateConfig, recordTaxAmountConfig, recordNonVATinclusiveAmountConfig,
      additionalRecordingPriceAmountConfig, checking, invoiceOptionsFetching, receiptTipImages, imageResult } = this.state;
    // let currencyEditable = invoiceUserFp['InvoiceControl.InvoiceCurrency.ALL.Editable'];
    let currencyEditable = true;
    let invoiceDate = "invoiceDate"; //开票日期
    let invoiceCode = "invoiceCode"; // 发票代码
    let invoiceNumber = "invoiceNumber";   // 发票号码
    let vatInvoiceCurrencyCode = "vatInvoiceCurrencyCode";  // 币种
    let nonVATinclusiveAmount = "nonVATinclusiveAmount";   // 总金额
    let taxRate = "taxRate"; // 税率
    let taxAmount = "taxAmount";   // 税额合计
    let priceTaxAmount = "priceTaxAmount";  // 价税合计
    let checkCode = "checkCode";  // 校验码
    let owner = "owner";  // 归属人
    let invoiceTypeNoValue = getFieldValue('invoiceTypeNo');
    let vatInvoiceCurrencyCodeValue = this.getFormItemValue(vatInvoiceCurrencyCode);
    let currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    console.log('receipt.slicingAttachment', receipt)
    // console.log('invoiceTypeNoValue', invoiceTypeNoValue)
    console.log("recordTaxRateConfig", recordTaxRateConfig)
    return (
      <Form className="create-invoice" onSubmit={this.handleSubmit}>
        <div className="ant-row" style={{ marginBottom: 20 }}>
          <div className="ant-col-8" style={{ marginRight: 10 }}></div>
          <div className="ant-col-10 ant-col-offset-1">
            {
              invoiceTypeNoValue && receiptTipImages[invoiceTypeNoValue] && (
                <Popover content={
                  receiptTipImages[invoiceTypeNoValue] && (
                    <img style={{ width: '35vw' }} src={receiptTipImages[invoiceTypeNoValue]} />
                  )}
                  overlayStyle={{ maxWidth: 'none' }}>
                  <div>
                    <Icon style={{
                      backgroundColor: "#4B8DFF",
                      color: '#fff',
                      borderRadius: '20px',
                      marginRight: 4,
                    }} type="info"></Icon>
                    {messages('my-account.key12')/*发票填写说明*/}
                  </div>
                </Popover>
              )
            }
          </div>
        </div>

        {/*OCR发票永远不可删除与修改*/}
        {receipt.cardsignType === 'OCR' && receipt.slicingAttachment && receipt.slicingAttachment.fileURL && (
          <FormItem label={messages('components.key1349')/*发票附件（最多上传1个附件）*/} {...formItemLayout}>
            <Condition>
              <If value={window.ISIE9}>
                <IeFileUpload defaultFileList={[receipt.originAttachment]} onChange={result => this.setState({ imageResult: result })} />
              </If>
              <Else>
                {getFieldDecorator('slicingAttachmentOID', {
                  rules: [{
                    required: invoiceTypeNoValue === '190' || invoiceTypeNoValue === '200' ? false : true,
                    message: `${messages("common.please.select")}`,
                  }],
                  initialValue: receipt.attachmentOID
                })(
                  <ImageUpload
                    defaultFileList={receipt.originAttachment ? [receipt.originAttachment] : []}
                    attachmentType="INVOICE_IMAGES"
                    // fileType={['jpg', 'png', 'jpeg', 'pdf', 'ofd']}
                    showFileName={false}
                    maxNum={1}
                    isUploading={value => this.setState({ imageIsUploading: value })}
                    onChange={result => this.setState({ imageResult: result })}
                    isExpense={true}
                    imageResult={this.state.imageResult}
                  />)}
              </Else>
            </Condition>
          </FormItem>
        )}
        <If value={receipt.cardsignType !== 'OCR' && this.checkInvoiceRender('image')}>
          <FormItem label={messages('components.key1349')/*发票附件（最多上传1个附件）*/} {...formItemLayout}>
            <Condition>
              <If value={window.ISIE9}>
                {getFieldDecorator('slicingAttachmentOID', {
                  rules: [{
                    required: invoiceTypeNoValue === '190' || invoiceTypeNoValue === '200' ? false : true,
                    message: `${messages("common.please.select")}`,
                  }],
                  initialValue: receipt.slicingAttachmentOID
                })(
                  <IeImgUpload
                    defaultFileList={receipt.slicingAttachment ? [receipt.slicingAttachment] : []}
                    attachmentType="INVOICE_IMAGES"
                    showFileName={false}
                    maxNum={1}
                  />
                )}
              </If>
              <Else>
                {getFieldDecorator('slicingAttachmentOID', {
                  rules: [{
                    required: invoiceTypeNoValue === '190' || invoiceTypeNoValue === '200' ? false : true,
                    message: `${messages("common.please.select")}`,
                  }],
                  initialValue: receipt.slicingAttachmentOID
                })(
                  <ImageUpload
                    defaultFileList={imageResult ? imageResult : receipt.slicingAttachment ? [receipt.slicingAttachment] : []}
                    attachmentType="INVOICE_IMAGES"
                    // fileType={['jpg', 'png', 'jpeg', 'pdf', 'ofd']}
                    showFileName={false}
                    maxNum={1}
                    isUploading={value => this.setState({ imageIsUploading: value })}
                    onChange={result => this.setState({ imageResult: result })}
                    isExpense={true}
                    imageResult={this.state.imageResult}
                  />
                )}
              </Else>
            </Condition>
          </FormItem>
        </If>
        <FormItem label={messages('my-account.key2')/*发票类型*/} {...formItemLayout}>
          {getFieldDecorator('invoiceTypeNo', {
            rules: [{
              required: true,
              message: messages("common.please.select")
            }]
          })(
            <Select
              dropdownMatchSelectWidth={false}
              onChange={this.handleReceiptNoChange}
              getPopupContainer={this.getPopupContainer}
              notFoundContent={invoiceOptionsFetching ? <Spin size="small" /> : messages('common.unmatched'/*无匹配结果*/)}
              placeholder={messages('common.please.select')/* 请选择 */}
              disabled={this.checkInvoiceRender('invoiceTypeNo', 3)}
            >
              {invoiceTypes.map(item => <Option key={item.value} style={{ whiteSpace: 'unset' }}>{item.messageKey}</Option>)}
            </Select>
          )}
        </FormItem>
        <div>
          {(this.checkInvoiceRender(invoiceCode) || this.showItemWithoutCode('billingCode')) &&
            <FormItem label={messages('my-account.key4')/*发票代码*/} {...formItemLayout}>
              {getFieldDecorator(invoiceCode, {
                rules: [{
                  required: this.checkInvoiceRender(invoiceCode, 2),
                  message: `${messages("common.please.enter")}`,
                }, {
                  validator: (rule, value, callback) => {
                    if (this.props.form.getFieldValue('invoiceTypeNo') === '180') {
                      callback();
                    }
                    if (value && value.length !== 10 && value.length !== 12 && value.length !== 14)
                      callback(messages('my-account.key400')/*发票代码位数填写有误*/);
                    else
                      callback();
                  }
                }]
              })(
                <Input
                  placeholder={this.props.form.getFieldValue('invoiceTypeNo') === '180' ? messages('common.please.input')/*请输入*/ : messages('my-account.key298')/*请输入10或12或14位数字或字母*/}
                  // placeholder={messages('my-account.key298')/*请输入10或12或14位数字或字母*/}
                  disabled={this.checkInvoiceRender(invoiceCode, 3)}
                />
              )}
            </FormItem>}
          {(this.checkInvoiceRender(invoiceNumber) || this.showItemWithoutCode('billingNo')) &&
            <FormItem label={messages('my-account.key6')/*发票号码*/} {...formItemLayout}>
              {getFieldDecorator(invoiceNumber, {
                rules: [{
                  required: this.checkInvoiceRender(invoiceNumber, 2),
                  message: messages("common.please.enter")
                }, {
                  max: 50,
                  message: messages('common.max.characters.length', { max: 50 }/*最多输入{max}个字符*/)
                }, {
                  pattern: '^[^\u4e00-\u9fa5]{1,}$',
                  message: messages('my-account.key238')/*不支持中文*/
                }, {
                  validator: (rule, value, callback) => {
                    if (!['112', '113'].includes(this.props.form.getFieldValue('invoiceTypeNo'))) {
                      callback();
                    }
                    if (value && value.length !== 20)
                      callback(messages('my-account.key400')/*发票代码位数填写有误*/);
                    else
                      callback();
                  }
                }]
              })(
                <Input
                  placeholder={['112', '113'].includes(this.props.form.getFieldValue('invoiceTypeNo')) ? messages('my-account.key401')/*请输入10或12或14位数字或字母*/ : messages('common.please.input')/*请输入*/}
                  disabled={this.checkInvoiceRender(invoiceNumber, 3)}
                />
              )}
            </FormItem>}
          {(this.checkInvoiceRender(invoiceDate) || this.showItemWithoutCode('billingTime')) && (
            <FormItem label={messages('my-account.key3')/*开票日期*/} {...formItemLayout}>
              {getFieldDecorator(invoiceDate, {
                rules: [{
                  required: this.checkInvoiceRender(invoiceDate, 2),
                  message: messages("common.please.enter")
                }]
              })(
                <DatePicker
                  placeholder={messages('common.please.select')}
                  style={{ width: '100%' }}
                  disabledDate={this.disabledDate}
                  getCalendarContainer={this.getPopupContainer}
                  disabled={this.checkInvoiceRender(invoiceDate, 3)}
                />
              )}
            </FormItem>
          )}
          {(this.checkInvoiceRender(taxRate)) &&
            <FormItem label={messages('my-account.key29')/*税率*/} {...formItemLayout}>
              {getFieldDecorator(taxRate, {
                rules: [{
                  required: (recordTaxRateConfig || this.checkInvoiceRender(taxRate, 2)),
                  message: messages("common.please.select")
                }]
              })(
                <Select placeholder={messages('common.please.select')}
                  getPopupContainer={this.getPopupContainer}
                  onChange={this.handleChangeTaxRate}>
                  {taxRates.map(tax => {
                    return <Option value={tax.taxRateValue} key={tax.taxRateValue}>{tax.taxRateKey}</Option>
                  })}
                </Select>
              )}
            </FormItem>}
          {(this.checkInvoiceRender(vatInvoiceCurrencyCode) || this.showItemWithoutCode('vatInvoiceCurrencyCode')) &&
            <FormItem label={messages('common.currency')/*币种*/} {...formItemLayout}>
              {getFieldDecorator(vatInvoiceCurrencyCode, {
                rules: [
                  {
                    required: this.checkInvoiceRender(vatInvoiceCurrencyCode, 2),
                    message: messages("common.please.select")
                  }
                ],
                initialValue: currency
              })(
                <Select dropdownMatchSelectWidth={false}
                  showSearch={true}
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  placeholder={messages('common.please.select')/* 请选择 */}
                  getPopupContainer={this.getPopupContainer}
                  onChange={this.selectVatInvoiceCurrencyCodeChange}
                  disabled={currencyEditable}>
                  {currencyList.map(item => {
                    return <Option
                      key={item.currency}>{item.currency}{language.code === 'zh_cn' ? ` ${item.currencyName}` : ''}</Option>
                  })}
                </Select>
              )}
            </FormItem>
          }

          {Number(invoiceTypeNoValue) === 150 && (
            <FormItem label={messages('common.total.amount')/*总金额*/} {...formItemLayout}>
              {getFieldDecorator('totalAmount')(
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={messages('my-account.key285')/*请输入行程单“合计”*/}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  onChange={value => this.handleAmountLinkage('totalAmount', value)}
                />
              )}
            </FormItem>
          )}

          {(this.checkInvoiceRender(priceTaxAmount)) &&
            <FormItem label={messages('my-account.key50')/*价税合计*/} {...formItemLayout}>
              {getFieldDecorator(priceTaxAmount, {
                rules: [{
                  required: additionalRecordingPriceAmountConfig || this.checkInvoiceRender(priceTaxAmount, 2),
                  message: messages("common.please.enter")
                }, {
                  //fix bug 25064 金额有最大值时，不能显示超过最大值的数据
                  validator: (rule, value, callback) => {
                    let max = 1000000000;
                    if (value === '-' || Math.abs(value) <= max || value === undefined) {
                      callback()
                    } else {
                      callback(messages('my-account.key169', { arg1: messages('my-account.key334')/*10亿*/ })/*最大值不能超过{arg1}*/)
                    }
                  }
                }]
              })(
                <InputNumber
                  min={-1000000000}
                  style={{ width: '100%' }}
                  placeholder={messages("common.please.enter")}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  onChange={value => this.handleAmountLinkage('priceTaxAmount', value)}
                />
              )}
            </FormItem>
          }

          {(Number(invoiceTypeNoValue) === 150 || this.showItemWithoutCode('nonDeductibleAmount')) &&
            <FormItem label={messages('my-account.key236')/*不可抵扣*/} {...formItemLayout}>
              {getFieldDecorator('nonDeductibleAmount', {
                rules: [{
                  required: true,
                  message: messages('common.please.enter')
                }]
              })(
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={messages('common.please.enter')}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  onChange={value => this.handleAmountLinkage('nonDeductibleAmount', value)}
                />
              )}
            </FormItem>
          }

          {(this.checkInvoiceRender(taxAmount)) &&
            <FormItem label={messages('my-account.key49')/*税额合计*/} {...formItemLayout}>
              {getFieldDecorator(taxAmount, {
                rules: [{
                  required: recordTaxAmountConfig || this.checkInvoiceRender(taxAmount, 2),
                  validator: this.handleValidator
                }]
              })(
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={messages('common.please.enter')}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  onChange={this.handleChangeTaxAmount} />
              )}
            </FormItem>
          }
          {(this.checkInvoiceRender(nonVATinclusiveAmount)) &&
            <FormItem label={`${messages('my-account.key48')/*金额合计*/}（${messages('my-account.key180')/*不含税*/}）`} {...formItemLayout}>
              {getFieldDecorator(nonVATinclusiveAmount, {
                rules: [{
                  required: recordNonVATinclusiveAmountConfig || this.checkInvoiceRender(nonVATinclusiveAmount, 2),
                  validator: this.handleValidator
                }]
              })(
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={messages('my-account.key11')/*请输入不含税金额*/}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  onChange={this.handleChangeNonVATinclusiveAmount}
                />
              )}
            </FormItem>
          }
          {(this.checkInvoiceRender(checkCode)) && (
            <FormItem label={messages('my-account.key8')/*校验码*/} {...formItemLayout}>
              {getFieldDecorator(checkCode, {
                rules: [{
                  required: this.checkInvoiceRender(checkCode, 2),
                  message: messages('common.name.is.required', { name: messages('my-account.key8')/*校验码*/ })
                }, {
                  min: 5,
                  message: messages('my-account.key156')/*请输入校验码后6位*/
                }, {
                  max: 6,
                  message: messages('my-account.key156')/*请输入校验码后6位*/
                }, {
                  pattern: '^[0-9a-zA-Z]{1,}$',
                  message: messages('my-account.key307')/*只支持数字和字母*/
                }]
              })(
                <Input
                  placeholder={messages('my-account.key156')/*请输入校验码后6位*/}
                  maxLength="6"
                  disabled={this.checkInvoiceRender(checkCode, 3)}
                />
              )}
            </FormItem>
          )}
          {(this.checkInvoiceRender(owner)) && (
            <FormItem label={messages('my-account.key246')/*归属人*/} {...formItemLayout}>
              {getFieldDecorator(owner, {
                rules: [{
                  required: this.checkInvoiceRender(owner, 2),
                  message: messages('my-account.key247')/*请输入归属人*/
                },
                {
                  max: 50,
                  message: messages('common.max.characters.length', { max: 50 })
                }
                ]
              })(
                <Input placeholder={messages('common.please.enter')} />
              )}
            </FormItem>
          )}
          {this.checkInvoiceRender('personInfo') && (
            <FormItem label={messages('my-account.key303')/*人员信息*/}{...formItemLayout}>
              {getFieldDecorator('showUserInfo', {
                rules: [{
                  required: this.checkInvoiceRender('personInfo', 2),
                  message: messages('common.please.select'/*请选择*/)
                }]
              })(
                <Select
                  getPopupContainer={triggerNode => triggerNode.parentNode}
                  allowClear
                  optionLabelProp="title"
                  placeholder={messages('common.please.select'/*请选择*/)}
                >
                  {showUserInfoOptions.map(item => (
                    <Option key={item.key} title={item.title} style={{ whiteSpace: 'unset' }}>{item.value}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          )}
        </div>
        <If value={this.isMoreInfoShow()}>
          <InvoiceMoreInfoEdit
            invoiceInfo={receipt}
            moreInfo={JSON.parse(receipt.moreInfo || "{}")}
            moreInfoLabel={JSON.parse(receipt.moreInfoLabel || "{}")}
            onChange={this.handleMoreInfoChange}
          />
        </If>
        <Row>
          <Col span={9} offset={9}>
            <Button type="primary" loading={checking} htmlType="submit">{messages('common.ok')/*确定*/}</Button>
            <Button onClick={onBack} style={{ marginLeft: 8 }}>{messages('common.back')/*返回*/}</Button>
          </Col>
          <Col span={5}>
          </Col>
        </Row>
      </Form>
    )
  };

  /**
   * 获取发票提示图片
   */
  getTipImg(invoiceTypeNoValue) {
    let receiptTipImages = this.state;
    if (receiptTipImages[invoiceTypeNoValue]) {
      return !1;
    }
    expenseService.getReceiptTipImg(invoiceTypeNoValue).then(res => {
      receiptTipImages[invoiceTypeNoValue] = res.data;
      this.setState({ receiptTipImages });
    })
  }
  /**
   * 不含税金额改变时修改税额
   * @param value
   */
  handleChangeNonVATinclusiveAmount = (value) => {
    const { getFieldsValue, setFieldsValue, getFieldValue } = this.props.form;
    let currencyCode = this.getFormItemValue('vatInvoiceCurrencyCode');
    let precision = queryCurrencyPrecision(currencyCode);
    let amount = getFieldValue('priceTaxAmount');
    let taxAmount = parseFloat((amount - value).toFixed(precision));
    if (!getFieldsValue().hasOwnProperty('taxAmount')) {
      return;
    }
    if (isNaN(taxAmount)) {
      setFieldsValue({ taxAmount: amount });
    } else {
      setFieldsValue({ taxAmount });
    }
  };

  //校验发票 显示：1(default)、必填：2、是否禁用：3
  checkInvoiceRender = (itemName, type = 1) => {
    const { receipt } = this.props;
    let { receiptConfigList } = this.state;
    let showAttr = false;
    let requiredAttr = false;
    // console.log("type", type)
    if (receiptConfigList && receiptConfigList.length > 0) {
      receiptConfigList.map(item => {
        if (item.valueCode === itemName) {
          showAttr = !(item.value === '10');
          requiredAttr = item.value === '30';
        }
      })
    }
    if (type === 3) {
      const types = ['ALICARDSIGN', 'APPCARDSIGN', 'JSCARDSIGN', 'WXFWCARDSIGN'];
      //区块链发票的校验码不可编辑（若识别的校验码若为空，或非5位，需要支持编辑）
      if (receipt.blockchain && itemName === 'checkCode') {
        return !!(receipt.checkCode && receipt.checkCode.length === 5);
      }
      //扫一扫
      if (receipt.cardsignType === 'SCANNING') {
        // 增值税卷式发票
        if (['11'].includes(receipt.invoiceTypeNo)) {
          return ['invoiceTypeNo', 'invoiceCode', 'invoiceNumber'].includes(itemName);
        }
        // 增值税发票、机动车销售发票
        else if (['01', '03'].includes(receipt.invoiceTypeNo)) {
          return ['invoiceTypeNo', 'invoiceCode', 'invoiceNumber', 'invoiceDate'].includes(itemName);
        }
        // 横版增值税发票
        else if (['04', '10', '14'].includes(receipt.invoiceTypeNo)) {
          return ['invoiceTypeNo', 'invoiceCode', 'invoiceNumber', 'invoiceDate', 'checkCode'].includes(itemName)
        }
      } else {
        return types.includes(receipt.cardsignType)
      }
    }
    return type === 1 ? showAttr : requiredAttr;
  };

  backInvoiceArea = () => {
    let { beforeReceipt } = this.state;
    this.setState({ currentStep: 0 }, () => {
      this.initReceiptValue(beforeReceipt)
    })
  };

  //日期限制
  disabledDate = (current) => {
    return current && current.valueOf() > Date.now();
  };

  auditSave = () => {
    const { resultReceipt, showOCRFlag } = this.state;
    const { close, onCreate } = this.props;
    this.setState({ auditSaving: true });
    this.saveReceipt(resultReceipt).then(result => {
      this.setState({ auditSaving: false });
      if (result) {
        onCreate ? onCreate(result, showOCRFlag) : close();
      }
    }).catch(e => {
      this.setState({ auditSaving: false });
    })
  };

  render() {
    const { loading, currentStep, resultReceipt, canSubmit, auditSaving, showOCRFlag } = this.state;
    const { onCreate, close, receipt, invoiceBagId, expenseReportId, fromVICP } = this.props;
    return (
      <div className="create-invoice">
        {
          currentStep === 0 ? (
            <Spin spinning={loading}>{this.renderInvoiceArea()}</Spin>
          ) : (
              <div style={{ paddingTop: 20 }}>
                <Invoice invoiceList={[resultReceipt]} canExpense={false} />
                {canSubmit && <div style={{ textAlign: 'center', marginBottom: 30 }}>
                  <a onClick={() => onCreate ? onCreate(receipt, showOCRFlag) : close()}
                    style={{ fontSize: 16 }}>{messages('my-account.key153')/*生成费用*/}&nbsp;&nbsp;
                  <Icon type="right-circle-o" /></a>
                </div>}
                {!canSubmit && (
                  <div style={{ textAlign: 'center', marginBottom: 30 }}>
                    <a onClick={this.backInvoiceArea} style={{ fontSize: 16 }}>
                      <Icon type="left-circle-o" />
                    &nbsp;&nbsp;{messages('common.back')/*返回*/}
                    </a>
                    <span style={{ marginLeft: 40 }}>
                      {(invoiceBagId || expenseReportId || fromVICP) && (
                        auditSaving ? <Spin /> : (
                          <a onClick={this.auditSave} style={{ fontSize: 16 }}>
                            <Icon type="check-circle-o" />
                            &nbsp;&nbsp;{messages('common.save')/*保存*/}
                          </a>
                        )
                      )}
                    </span>
                  </div>
                )}
              </div>
            )
        }
      </div>
    )
  }
}

CreateInvoice.propTypes = {
  onCreate: React.PropTypes.func,
  onBack: React.PropTypes.func,
  createType: React.PropTypes.number,
  receipt: React.PropTypes.any,
  invoiceOID: React.PropTypes.any,//费用oid可传空
  currencyList: React.PropTypes.array,//费用币种list
  invoiceUserFp: React.PropTypes.object,//申请人费用FP
  receiptOperateScene: React.PropTypes.number, //发票操作场景：1.发票创建费用；2.费用新增发票；3.费用编辑发票
  receiptList: React.PropTypes.array, //添加到费用里面的发票
  userOID: React.PropTypes.string,//用户发票
  currency: React.PropTypes.string,
  pageFrom: React.PropTypes.string,
};

CreateInvoice.defaultProps = {
  createType: 1,//1.是员工//2是财务
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    documentaryCompany: state.login.documentaryCompany,
    language: state.main.language
  }
}

const WrappedCreateInvoice = Form.create()(CreateInvoice);

export default connect(mapStateToProps)(WrappedCreateInvoice);
